/**
 * Created with IntelliJ IDEA.
 * Description:
 * User:
 * Date: 2024-10-17
 * Time: 10:16
 */
public class BinarySearchTree {
    static class TreeNode {
        public int val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(int val){
            this.val = val;
        }
    }

    public TreeNode root;

    //插入数据
    public void insert(int key){
        if(root == null){
            root = new TreeNode(key);
            return;
        }
        TreeNode parent = null;
        TreeNode node = new TreeNode(key);
        TreeNode cur = root;
        while(cur != null){
            if(cur.val < key){
                parent = cur;
                cur = cur.right;
            }else if(cur.val > key){
                parent = cur;
                cur = cur.left;
            }else{
                //不能存在两个一样的数
                return;
            }
        }
        if(parent.val < key){
            parent.right = node;
        }else{
            parent.left = node;
        }
    }

    //查找数据
    public TreeNode search(int key){
        TreeNode cur = root;
        while(cur != null){
            if(cur.val < key){
                cur = cur.right;
            }else if(cur.val > key){
                cur = cur.left;
            }else{
                return cur;
            }
        }
        return null;
    }

    public void remove(int key){
        TreeNode cur = root;
        TreeNode parent = null;
        while(cur != null){
            if(cur.val < key){
                parent = cur;
                cur = cur.right;
            }else if(cur.val > key){
                parent = cur;
                cur = cur.left;
            }else{
                removeNode(parent, cur);
                return;
            }
        }
    }

    private void removeNode(TreeNode parent, TreeNode cur) {
        if(cur.left == null){
            if(root == cur){
                root = cur.right;
            }else if(cur == parent.left){
                parent.left = cur.right;
            }else{
                parent.right = cur.right;
            }
        }else if(cur.right == null){
            if(cur == root){
                root = cur.left;
            }else if(cur == parent.left){
                parent.left = cur.left;
            }else{
                parent.right = cur.left;
            }
        }else{
            TreeNode targetParent = cur;
            TreeNode target = cur.right;
            while(target.left != null){
                targetParent = target;
                target = target.left;
            }

            cur.val = target.val;
            if(targetParent.left == target){
                targetParent.left = target.right;
            }else{
                targetParent.right = target.right;
            }

        }
    }
}
